package com.lufan.interceptor;

import com.lufan.util.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class UserInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(UserInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 从请求头中获取Cookie
        String cookieHeader = request.getHeader("Cookie");
        if (cookieHeader != null && !cookieHeader.isEmpty()) {
            // 解析Cookie字符串，查找SESSDATA
            String[] cookies = cookieHeader.split(";");
            for (String cookie : cookies) {
                String[] parts = cookie.trim().split("=", 2);
                if (parts.length == 2 && "SESSDATA".equals(parts[0].trim())) {
                    String sessdata = parts[1].trim();
                    UserContext.setSessdata(sessdata);break;
                }
            }
        } else {
            logger.warn("请求中未找到Cookie头");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        UserContext.clear();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.clear();
    }
} 